<template>
  <div class="cart-page">
    <div class="cart-list" v-if="cartStore.items.length > 0">
      <van-swipe-cell v-for="item in cartStore.items" :key="item.id">
        <van-card
          :num="item.quantity"
          :price="item.price"
          :title="item.name"
          :thumb="item.image"
          :desc="item.spiceLevels ? `规格: ${item.spiceLevels}` : ''"
          @click="toggleSelection(item)"
        >
          <template #footer>
            <van-stepper
              v-model="item.quantity"
              integer
              min="0"
              @change="(val:any) => updateQuantity(item.id??0, val)"
            />
          </template>
        </van-card>
      </van-swipe-cell>
      <van-submit-bar
        :price="(cartStore.totalPrice || 0) * 100"
        button-text="提交订单"
        @submit="onSubmit"
      />
    </div>

    <van-empty v-else description="购物车是空的">
      <van-button round type="primary" @click="router.push('/')">去逛逛</van-button>
    </van-empty>
  </div>
</template>

<script setup lang="ts">
import { useCartStore } from "@/store/cart";
import { AxiosQ } from "@/tool/http";
import { getCompany_id, getUser_name } from "@/tool/login";
import { Url } from "@/tool/url";
import { showToast } from "vant";
import { useRouter } from "vue-router";

const cartStore = useCartStore();
const router = useRouter();

const toggleSelection = (item: any) => {
  item.selected = !item.selected;
};

const updateQuantity = (id: number, quantity: number) => {
  if (quantity === 0) {
    cartStore.removeItem(id);
  } else {
    cartStore.updateQuantity(id, quantity);
  }
};

const onSubmit = () => {
  const selectedItems = cartStore.items.map((item) => {
    return { id: item.id, number: item.quantity,description:item.spiceLevels?.join(",") };
  });
  console.log(selectedItems);

  // 提交选中的商品
  AxiosQ("POST",Url.record,{
    data:{
      company_id:getCompany_id(),
      orders:selectedItems,
      name:getUser_name()+"_的订单" + new Date().getTime()
    }
  }).then(res=>{
    showToast({ message:res.data+ "请联系店员进行付款" });
    cartStore.clearCart();
  })
  
};
</script>

<style scoped lang="scss">
.cart-page {
  .van-submit-bar {
    bottom: 50px;
    max-width: 390px;
    left: 39.8%;
  }

  .cart-list {
    display: grid;
    gap: 10px;
  }
  padding-bottom: 50px;
}
.delete-button {
  height: 100%;
}
.cart-item {
  display: flex;
  align-items: center;
  padding: 10px;
}
.van-card {
  flex: 1;
}
.van-checkbox {
  margin-right: 10px;
}
</style>
